<template>
    <Card class="no-border-card">
        <p slot="title">日志</p>

        <Row :gutter="20" class="margin-bottom-20">
            <i-col :span="5">
                <Select
                    v-model="indexOne"
                    placeholder="全部"
                    clearable
                    @on-change="handleOptionChange(1)">
                    <Option
                        v-for="(lv1, lv1Index) in operationTypes"
                        :value="lv1Index"
                        :key="lv1.id">
                        {{lv1.name}}
                    </Option>
                </Select>
            </i-col>
            <i-col :span="5">
                <Select
                    v-model="indexTwo"
                    placeholder="全部"
                    clearable
                    @on-change="handleOptionChange(2)">
                    <Option
                        v-for="(lv2, lv2Index) in lv2Options"
                        :value="lv2Index"
                        :key="lv2.id">
                        {{lv2.name}}
                    </Option>
                </Select>
            </i-col>
            <i-col :span="5">
                <Select
                    v-model="indexThree"
                    placeholder="全部"
                    clearable>
                    <Option
                        v-for="(lv3, lv3Index) in lv3Options"
                        :value="lv3Index"
                        :key="lv3.id">
                        {{lv3.name}}
                    </Option>
                </Select>
            </i-col>
            <i-col :span="5">
                <DatePicker
                    :clearable="false"
                    type="daterange"
                    style="width:100%;"
                    v-model="timeRange"
                    placeholder="选择时间段"
                />
            </i-col>
            <Button type="primary" icon="ios-search-strong" style="padding:4px 0px 3px;" @click="handleSearch"></Button>
        </Row>

        <!--日志数据-->
        <Table border stripe :columns="columns" :data="tableData" :loading="loading"></Table>
        <!--日志数据end-->

        <div class="text-center">
            <Page
                show-total
                show-elevator
                :total="pagination.total"
                :page-size="pagination.limit"
                :current.sync="pagination.current"
                @on-change="getOperateData"
            />
        </div>
    </Card>
</template>

<script>
    import debounce from 'lodash/debounce'
import { http, api } from '@/libs/http'
import { twoDaysAgo, now, searchTimeRange, dayTimeStamp, date } from '@/libs/date'

export default {
      name: 'saas-log',
      data () {
        return {
          loading: false,
          tableData: [],
          indexOne: '',
          indexTwo: '',
          indexThree: '',
          operationTypes: [],
          timeRange: [ twoDaysAgo, now ],
          pagination: {
            total: 0,
            current: 1,
            limit: 20
          },
          columns: [
            { title: '说明', key: 'opName' },
            { title: '结果', key: 'opResult' },
            { title: '范围', key: 'opRange' },
            { title: '时间', key: 'date', align: 'center', width: 140 },
            { title: '操作者', key: 'userName', align: 'center', width: 120 },
            { title: '状态', key: 'opStatus', align: 'center', width: 100 }
          ]
        }
      },
      computed: {
        lv2Options () {
          const { operationTypes, indexOne } = this
          if (!operationTypes[indexOne]) return []
          return operationTypes[indexOne].children
        },
        lv3Options () {
          const { operationTypes, indexOne, indexTwo } = this
          if (!operationTypes[indexOne] || !operationTypes[indexOne].children[indexTwo]) return []
          return operationTypes[indexOne].children[indexTwo].children
        }
      },
      created () {
        this.getOperationTypes()
        this.getOperateData(1)
      },
      methods: {
        handleSearch: debounce(function () {
          this.getOperateData(1)
        }, 250),
        handleOptionChange (deep) {
          if (deep < 3) this.indexThree = ''
          if (deep < 2) this.indexTwo = ''
        },
        async getOperationTypes () {
          const res = await http.req(api.operations_types)
          if (!res) return
          this.operationTypes = res.rows
        },
        getQuery () {
          const {
            indexOne, indexTwo, indexThree, pagination: { limit, current }
          } = this
          const [ start_time, end_time ] = searchTimeRange(this.timeRange)
          const query = {
            start_time,
            end_time,
            limit,
            offset: limit * (current - 1)
          }
          if (Number.isInteger(indexThree)) {
            query.type_code = this.operationTypes[indexOne].children[indexTwo].children[indexThree].code
          } else if (Number.isInteger(indexTwo)) {
            query.parent_id = this.operationTypes[indexOne].children[indexTwo].id
          } else if (Number.isInteger(indexOne)) {
            query.parent_id = this.operationTypes[indexOne].id
          }
          return query
        },
        async getOperateData (page) {
          if (page === 1) this.pagination.current = 1

          const query = this.getQuery()
          const { start_time, end_time } = query
          const monthTimestamp = 30 * dayTimeStamp

          if (!start_time || !end_time || (end_time - start_time > monthTimestamp)) {
            this.$Message.info('查询时间不能大于30天')
            return
          }

          try {
            this.loading = true
            const res = await http.req(api.operations, null, query)
            this.tableData = this.formatListData(res.rows)
            this.pagination.total = res.count || 0
          } catch (err) {
            console.log(err)
          } finally {
            this.loading = false
          }
        },
        formatListData (list) {
          return list.map(item => {
            const {
              operation_type: { name: opName } = {},
              target: { name: opRange, value: opResult } = {},
              time, user_name: userName = '', res_state
            } = item
            const opStatus = res_state === 1 ? '成功' : '失败'
            return {
              opName,
              userName,
              opRange: opRange || '-',
              opResult: opResult || '-',
              date: date(time, 'YYYY-MM-DD HH:mm'),
              opStatus: opName.includes('绑定') ? '' : opStatus
            }
          })
        }
      }
    }
</script>